<template>
  <div class="login-form">
    <el-form :model="form" @submit.prevent="handleSubmit">
      <el-form-item>
        <el-input
          v-model="form.email"
          placeholder="邮箱"
          type="email"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="form.password"
          placeholder="密码"
          type="password"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isLogin ? '登录' : '注册' }}
        </el-button>
        <el-button type="text" @click="isLogin = !isLogin">
          {{ isLogin ? '没有账号？去注册' : '已有账号？去登录' }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { login, register } from '../api/shortener'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router' 

const router = useRouter()
const loading = ref(false)
const isLogin = ref(true)

const form = ref({
  email: '',
  password: ''
})

const handleSubmit = async () => {
  if (!form.value.email || !form.value.password) {
    ElMessage.warning('请填写完整信息')
    return
  }

  loading.value = true
  try {
    const response = isLogin.value
      ? await login(form.value.email, form.value.password)
      : await register(form.value.email, form.value.password)
    
    localStorage.setItem('token', response.access_token)
    ElMessage.success(isLogin.value ? '登录成功' : '注册成功')
    router.push('/')
  } catch (error) {
    ElMessage.error(error.response?.data?.detail || '操作失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-form {
  max-width: 400px;
  margin: 40px auto;
  padding: 20px;
}
</style> 